package com.bluemsun.naturallanguageprocessing.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author ：hj
 * @date ：Created in 2021/1/22 11:17
 * @description：redis工具类
 * @modified By：
 * @version: $
 */
@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    //获取值
    public String get(final String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

//    public void contextLoads(String key){
//        //操作redis的一个对象
//        BoundValueOperations<Spring,Object> ops = redisTemplate.boundValueOps("key");
//        //获得key对应的值
//        Object o = ops.get();
//        //无该值
//        if(o==null){
//
//        }else{
//
//        }
//    }
    /**
     * 写入缓存
     */
    public boolean set(final String key, String value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    //设置有效时间
    public boolean setEx(final String key, String value, long timeout) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value,timeout,TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 更新缓存
     */
    public boolean getAndSet(final String key, String value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().getAndSet(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除缓存
     */
    public boolean del(final String key) {
        boolean result = false;
        try {
            redisTemplate.delete(key);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
   public Set<String> keys(String pattern){

       Set<String> set = redisTemplate.keys(pattern);
       return set;
   }


}


